package com.example.express.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {

    private static DataSource dataSource;

    static {
        try {
            Properties properties = new Properties();
            properties.load(DruidUtils.class.getClassLoader().getResourceAsStream("db.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public static void close(Connection conn, Statement state, ResultSet resultSet){

        try {
            if(resultSet!=null)
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if (state!=null)
            state.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if (conn!=null)
            conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
